package com.qire.manhua.view.comicReader;

import android.graphics.Canvas;
import android.graphics.Rect;

import com.qire.manhua.view.comicReader.renderer.BulletScreen;
import com.qire.manhua.view.comicReader.renderer.BulletScreenPool;
import com.qire.manhua.view.comicReader.renderer.PictureResource;

import java.util.Arrays;

/**
 * 弹幕渲染器
 */
public class BulletScreenRenderer {

    private BulletScreenPool pool;

    private boolean followMoving = true, isPause = true;

    private int scrollX=0, scrollY=0;

    public BulletScreenRenderer() {
        this(new BulletScreenPool());
    }

    public BulletScreenRenderer(BulletScreenPool pool) {
        this.pool = pool;
    }

    public void loadBulletScreen(String key, BulletScreen bulletScreen) {
    	pool.loadBulletScreen(key, bulletScreen);
    }
    
    public void scrollTo(int x,int y) {
        scrollX = x;
        scrollY = y;
    }

    public void scrollBy(int x,int y) {
        scrollTo(scrollX + x, scrollY + y);
    }

    public void pause(){
        isPause = true;
    }

    public void goPlay(){
        isPause = false;
    }

    public void draw(Canvas canvas, Rect screenArea, PictureResource[] visiblePictureResources) {
        canvas.save();
        //TODO:弹幕需要跟随屏幕移动 followMoving=true;
        if(followMoving) {
            canvas.translate(scrollX,scrollY);
        }
        BulletScreen[] bulletScreens = pool.fetchVisibleBulletScreen(screenArea, visiblePictureResources);
        BulletScreen[] tempBullets = Arrays.copyOf(bulletScreens, bulletScreens.length);

        for(BulletScreen bulletScreen : tempBullets) {
        	if(bulletScreen!=null) {
                bulletScreen.playState(isPause);
                bulletScreen.draw(canvas);
            }
        }
        canvas.restore();
    }
    
    public void release() {
    	if(pool!=null) {
    		pool.release();
//    		pool=null;
    	}
    }
}
